<template>
  <el-card v-loading="paperLoading" element-loading-text="提交中" shadow="always">
    <el-form label-position="top" :disabled="notWrite" :model="que" size="mini" ref="paperForm">
      <author prop="_01" :rules="rules" :que="que._01" label="专利申请者(所有者)" click="null" :notWrite="notWrite" />
      <el-form-item prop="_02" :rules="rules" label="专利题名">
        <el-input v-model.trim="que._02"></el-input>
      </el-form-item>
      <el-form-item prop="_03" label="专利国别">
        <el-select
          style="width:50%"
          v-model="que._03"
          filterable
          allow-create
          default-first-option
          placeholder="请选择，亦可直接输入"
        >
          <el-option v-for="item in publication" :key="item.value" :label="item.value" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :rules="rules" prop="_04" class="cell-12" label="专利号">
        <el-input v-model.trim="que._04"></el-input>
      </el-form-item>
      <el-form-item prop="_05" :rules="rules" class="cell-12 space" label="授权日期">
        <el-date-picker
          v-model="que._05"
          type="date"
          placeholder="选择日期"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </el-form-item>
      <el-form-item prop="_06" class="cell-12" label="授权情况">
        <el-radio-group v-model="que._06">
          <el-radio label="授权">已授权</el-radio>
          <el-radio label="未授权">未授权</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="_07" :rules="rules" label="专利类型">
        <el-radio-group v-model="que._07">
          <el-radio label="发明专利">发明专利</el-radio>
          <el-radio label="实用新型专利">实用新型专利</el-radio>
          <el-radio label="外观设计专利">外观设计专利</el-radio>
          <el-radio label="软件著作权">软件著作权</el-radio>
          <el-radio label="其他">其他</el-radio>
        </el-radio-group>
      </el-form-item>
      <fileUpload
        :token="token"
        :createTime="createTime"
        @filePath="getFileData"
        :oldFileData="oldfiles"
        @deleteFile="files = files.filter((s) => s.name != $event)"
      />
      <el-form-item v-if="!notWrite" class="formButton">
        <el-button @click="$goback()">返回</el-button>
        <!-- <el-button type="primary">下载模板填写</el-button>
        <el-button type="primary">导入已填写</el-button>-->
        <el-button type="danger" plain @click="resetForm('paperForm')">重置</el-button>
        <el-button type="primary" @click="submitForm('paperForm')">提交</el-button>
      </el-form-item>
    </el-form>
    <div class="formButton" style="margin-bottom:18px" v-if="notWrite">
      <el-button size="mini" type="primary" @click="$goback()">返回</el-button>
      <el-button v-if="!isAdmin" size="mini" type="primary" @click="currentItem.status == '审核通过' ? '' : updateForm()">{{
        currentItem.status == "审核通过" ? "审核通过，无需修改" : "修改"
      }}</el-button>
      <template v-else>
        <template v-if="currentItem.status != '审核通过'">
          <el-button size="mini" type="danger" @click="reviewItem('审核未通过')">审核未通过</el-button>
          <el-button size="mini" type="primary" @click="reviewItem('审核通过')">审核通过</el-button>
        </template>
      </template>
    </div>
  </el-card>
</template>

<script>
let BaaS = window.BaaS;
import { addData, updateData, reset } from "@/assets/crud";
import author from "@/components/author";
import fileUpload from "@/components/fileUpload";
export default {
  components: { author, fileUpload },
  props: ["token"],
  data() {
    return {
      files: [],
      oldfiles: [],
      createTime: this.getNewTime(),
      isAdmin: false,
      paperLoading: false,
      notWrite: false,
      isNew: true,
      currentItem: {},
      status: "未审核",
      // 以下可修改
      docType: "专利",
      publication: [
        {
          value: "中国",
        },
        {
          value: "美国",
        },
      ],
      que: {
        _01: [],
        _02: "",
        _03: "",
        _04: "",
        _05: "",
        _06: "授权",
        _07: "",
      },
      // 以上可修改
      rules: {
        required: true,
        message: "该项必填",
        trigger: "change",
      },
      // 时间不准选未来时间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  methods: {
    //   表单全部验证，记得做提交前弹出模态框，和提交成功提示
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交？", {
            confirmButtonText: "确定",
            cancelButtonText: "再看看",
            type: "info",
          })
            .then(() => {
              this.paperLoading = true;
              this.submitData();
            })
            .catch((err) => err);
        } else {
          return false;
        }
      });
    },
    // 表单重置，记得做重置前弹出模态框
    resetForm(formName) {
      reset(this, formName);
    },
    // 格式化回答项
    // A
    formatQue(que) {
      let names = JSON.parse(JSON.stringify(que));
      let all = names._01.map((i) => {
        if (i.type == "") {
          i.name = i.name + "*";
        }
        return i.name;
      });
      let files = {
        time: this.createTime,
        path: this.files,
      };
      return {
        a: all.join(",") + ".",
        b: names._05.split("-")[0],
        c: names._05.split("-")[1],
        d: names._05.split("-")[2],
        files,
      };
    },
    // 提交表单
    submitData() {
      let submit = {
        answer: JSON.stringify(Object.assign(this.que, this.formatQue(this.que))),
        docType: this.docType,
        status: this.status,
      };
      if (this.isNew) {
        addData("answer", submit)
          .then(() => {
            this.$message.success("提交成功！");
            setTimeout(() => {
              this.$goback();
            }, 300);
          })
          .catch(() => {
            this.$message.error("提交失败！请检查");
          });
      } else {
        updateData("answer", this.currentItem.id, submit)
          .then(() => {
            this.$message.success("修改成功！");
            setTimeout(() => {
              this.$goback();
            }, 300);
          })
          .catch(() => {
            this.$message.error("提交失败！请检查");
          });
      }
    },
    // 本地存储中拉取当前项
    getItemFromStorage() {
      let item = BaaS.storage.get("currentItem");
      if (item) {
        this.currentItem = item;
        this.que = JSON.parse(item.answer);
        this.notWrite = true;
        this.isNew = false;
        if ("files" in this.que) {
          this.files = this.que.files.path;
          this.oldfiles = this.que.files.path;
          this.createTime = this.que.files.time;
        }
        BaaS.storage.set("currentItem", "");
      }
    },
    updateForm() {
      this.notWrite = false;
    },
    reviewItem(review) {
      updateData("answer", this.currentItem.id, "status", review).then(
        () => {
          this.$message.success("操作成功！");
          this.$goback();
        },
        (err) => err
      );
    },
    getNewTime() {
      let time = new Date().getTime().toString();
      if (time.length == 13) {
        time = time.substring(0, 10);
      }
      return `item_patent_${time}`;
    },
    getFileData(value) {
      this.files.push(value);
    },
  },
  watch: {},
  computed: {},
  created() {
    this.isAdmin = BaaS.storage.get("ok");
    this.getItemFromStorage();
  },
  mounted() {
    this.$emit("doc", this.docType);
  },
  beforeRouteEnter(to, from, next) {
    if (!window.$login) {
      BaaS.auth
        .getCurrentUser()
        .then(() => {
          window.$login = true;
          next();
        })
        .catch(() => {
          next({ name: "login" });
        });
    } else {
      if (BaaS.storage.get("ok") && from.name == null) {
        next({ name: "table" });
      } else {
        next();
      }
    }
  },
};
</script>

<style scoped>
.cell-12 {
  display: inline-block;
  width: 48%;
}
.cell-13 {
  display: inline-block;
  width: 30%;
}
.space {
  margin-left: 20px;
}
.formButton {
  text-align: right;
  margin-top: 30px;
  width: 100%;
}
</style>
